<script lang="jsx">
import { defineComponent, h, resolveComponent, computed, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { MenuUnfoldOutlined, MenuFoldOutlined } from "@ant-design/icons-vue"; // Import icons

export default defineComponent({
  name: "SideBarItem",
  props: {
    collapsed: {
      type: Boolean,
      default: false,
    },
  },
  setup(props) {
    const router = useRouter();
    const collapsed = ref(props.collapsed);
    const openKeys = ref([]); // 展开的一级菜单 key
    const selectedKeys = ref([]); // 高亮的二级菜单 key

    // 获取路由表
    const routes = computed(() => {
      return router.options.routes.filter((v) => !v.hidden);
    });

    watch(
      () => router.currentRoute.value,
      (route) => {
        openKeys.value = [route?.meta.parent];
        selectedKeys.value = [route?.path];
      },
      { immediate: true }
    );

    // 渲染侧栏菜单的函数
    const renderSubMenu = () => {
      function travel(_route, nodes = []) {
        if (_route) {
          _route.forEach((element) => {
            const { icon, title } = element.meta;
            const node =
              element.children && element.children.length > 0 ? (
                <a-sub-menu
                  title={title}
                  key={element.name}
                  icon={h(resolveComponent(icon))}
                >
                  {travel(element.children)}
                </a-sub-menu>
              ) : (
                <a-menu-item key={element.path}>
                  <router-link to={element.path}>{title}</router-link>
                </a-menu-item>
              );
            nodes.push(node);
          });
        }
        return nodes;
      }
      return travel(routes.value);
    };

    // 切换折叠状态
    const toggleCollapse = () => {
      collapsed.value = !collapsed.value;
    };

    return () => (
      <a-layout-sider
        theme="light"
        width="240"
        class="sidebar"
        collapsed={collapsed.value}
      >
        {/* Logo */}
        <h1 class="logo">
          <RouterLink to="/">Logo</RouterLink>
        </h1>
        {/* 菜单 */}
        <a-menu
          v-model:openKeys={openKeys.value}
          v-model:selectedKeys={selectedKeys.value}
          theme="light"
          mode="inline"
        >
          {renderSubMenu()}
        </a-menu>
        {/* 折叠按钮 */}
        <div class="open_close" onClick={toggleCollapse}>
          {collapsed.value ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
        </div>
      </a-layout-sider>
    );
  },
});
</script>

<style scoped lang="scss">
.sidebar {
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  z-index: 99;
  height: 100vh;
  overflow-y: auto;
}
.logo {
  height: 150px;
  display: flex;
  justify-content: center;
  align-items: center;

  &-img {
    width: 152px;
    height: 113px;
  }
}
.open_close {
  position: absolute;
  right: 20px;
  bottom: 50px;
  cursor: pointer;
}
</style>
